package jsen.tool.ddd.adapter.infrastructure.specification.base;

import jsen.tool.ddd.adapter.infrastructure.specification.ISpecification;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;

/**
 * sdl解析语句后，需要找到对应的ISpecification，这个类用于获取ISpecification
 *
 * @author jsen
 * @date 2021/10/6
 */
public class SdlDefaultSpecificationSupplier {
    private static final Map<String, Supplier<? extends ISpecification<?>>> specMap = new HashMap<>();

    public static <T> void register(String spec, Supplier<ISpecification<T>> supplier) {
        specMap.put(spec, supplier);
    }

    @SuppressWarnings("unchecked")
    static <T> ISpecification<T> getSpec(String spec) {
        Supplier<? extends ISpecification<?>> supplier = specMap.get(spec);
        if (supplier != null) {
            return (ISpecification<T>) supplier.get();
        }
        throw new IllegalArgumentException("请先调用SpecificationFactory.register 或 " +
                "SdlDefaultSpecificationSupplier.register注册名为[" + spec + "]的规格");
    }
}
